package com.pingba.serviceImpl.friend;

import com.pingba.dao.BaseDao;
import com.pingba.dao.friend.FriendApplyDao;
import com.pingba.entity.friend.FriendApply;
import com.pingba.service.friend.FriendApplyService;
import com.pingba.service.friend.FriendRelationService;
import com.pingba.serviceImpl.BaseServiceImpl;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2015/11/9 0009.
 */
@Service("FriendApplyService")
public class FriendApplyServiceImpl extends BaseServiceImpl<FriendApply, Long> implements FriendApplyService {

    private static Logger logger = Logger.getLogger(FriendApplyServiceImpl.class);
    @Autowired
    private FriendApplyDao friendApplyDao;

    @Autowired
    private FriendRelationService friendRelationService;

    @Override
    public BaseDao<FriendApply, Long> getDao() {
        return friendApplyDao;
    }

    @Override
    public List<FriendApply> getMyApplySendHistory(long userId) {
        return friendApplyDao.getMyApplySendHistory(userId);
    }

    @Override
    public List<FriendApply> getMyUnhandled(long userId) {
        return friendApplyDao.getMyUnhandled(userId);
    }

    @Override
    public List<FriendApply> getMyApplyRcvHistory(long userId) {
        return friendApplyDao.getMyApplyRcvHistory(userId);
    }

    @Override
    public void setHandled(long fromUserId, long toUserId) {
        friendApplyDao.setHandled(fromUserId, toUserId);
    }

    @Override
    public void setAllHandled(long toUserId) {
        friendApplyDao.setAllHandled(toUserId);
    }

    @Override
    public boolean addApply(FriendApply apply) {
        if (friendApplyDao.find(apply) != null) {
            return false;
        }
        apply.setStatus(FriendApply.StatusDefault);
        apply.setHandled(false);
        apply.setApplyTime(new Date().getTime());
        friendApplyDao.insert(apply);
        return true;
    }


    @Override
    public void agree(long fromUserId, long toUserId) {
        friendApplyDao.updateStatus(fromUserId, toUserId, FriendApply.StatusAgree);
        if (friendRelationService.isFriend(fromUserId, toUserId)) {
            logger.info("has been friend, return");
            return ;
        }
        friendRelationService.beFriends(fromUserId, toUserId, new Date().getTime());
    }

    @Override
    public void deny(long fromUserId, long toUserId) {
        friendApplyDao.updateStatus(fromUserId, toUserId, FriendApply.StatusDeny);

    }
}
